<?php

declare(strict_types=1);

namespace App\Resource\Activity\Summer\Reward;

use App\Models\ActivityDB\Summer2022RewardSetting;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Resources\Json\JsonResource;

class Resource extends JsonResource
{
    /**
     * 格式化数据
     *
     * @param Collection $data
     * @return array
     */
    public static function format(Collection $data): array
    {
        $res = [];
        foreach ($data as $datum) {
            $res[$datum->rank]['rank'] = $datum->rank;
            $res[$datum->rank]['rank_name'] = $datum->rank === 4 ? "第4-10名" : "第{$datum->rank}名";
            if ($datum->reward_type === Summer2022RewardSetting::REWARD_TYPE_GIFT) {
                $res[$datum->rank]['gift'][] = [
                    'id' => $datum->gift->id,
                    'name' => $datum->gift->name,
                    'picture' => $datum->gift->picture,
                    'type' => Summer2022RewardSetting::REWARD_TYPE_GIFT,
                    'count' => $datum->reward_count,  // 礼物都是1个
                    'period' => $datum->period,  // 礼物没有过期时间
                    'order' => 0,
                ];
            } else {
                $res[$datum->rank]['reward'][] = [
                    'id' => $datum->reward->id,
                    'name' => $datum->reward->name,
                    'picture' => $datum->reward->picture,
                    'type' => $datum->reward->type,
                    'count' => $datum->reward_count,
                    'period' => $datum->period . '天',
                    'order' => $datum->reward->order,
                ];
            }
        }
        # TODO  搜索数据的时候做好排序
        foreach ($res as &$datum) {
            $order = array_column($datum['reward'], 'order');
            array_multisort($order, SORT_ASC, $datum['reward']);
            unset($datum);
        }
        ksort($res);

        return array_values($res);
    }
}
